package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

import static com.hmdp.utils.RedisConstants.SHOP_TYPE_LIST_KEY;

@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ShopType getId(int id) {
        QueryWrapper<ShopType> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ShopType::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public List<ShopType> queryByRedis() {
        //创造key
        String key = SHOP_TYPE_LIST_KEY;
        //从redis里面找
        String shop_type_list = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shop_type_list)) {
            //找得到就返回成list（序列化）
            return JSONUtil.toList(shop_type_list, ShopType.class);
        }
        //redis缓存里面没有 则从数据库里面找
        List<ShopType> list = this.list(new LambdaQueryWrapper<ShopType>().orderByAsc(ShopType::getSort));
        if (list == null || list.isEmpty()) {
            //找不到 那就返回空的
            return Collections.emptyList();
        }
        //找到了 先返回给redis缓存来保存
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(list));
        //再返回给前端即可
        return list;
    }
}
